<template>
  <ElCard class="w-full">
    <div class="production-plan-list">
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="计划编号">
            <el-input v-model="searchForm.code" clearable placeholder="请输入计划编号"></el-input>
          </el-form-item>
          <el-form-item label="计划时间">
            <el-date-picker v-model="searchForm.planTime" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="info" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action-bar">
        <div class="action-bar-left">
          <el-button type="primary" @click="addNewPlan">新增</el-button>
          <el-button type="primary" @click="exportData">导出</el-button>
          <el-button type="primary" @click="showUpload">导入</el-button>
        </div>
        <div class="action-bar-right">
          <el-radio-group v-model="showType">
            <el-radio-button :value="0">按单</el-radio-button>
            <el-radio-button :value="1">按明细</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <el-table v-if="showType === 0" :data="productionPlans" v-loading="loadingTable" style="width: 100%" :style="{ height: `${tableHeight *0.74}px` }">
        <el-table-column prop="productionPlanCode" width="200" label="计划编号" align="center">
          <template #header>
            <table-header-filter label="计划编号" :bind-data="searchForm.code" type="input" filterField="code" @change="filterChangeEvent"></table-header-filter>
          </template>
        </el-table-column>
        <el-table-column prop="planTime" width="180" label="计划时间" align="center">
        </el-table-column>
        <el-table-column prop="materialNumber" width="100" label="物料个数" align="center"></el-table-column>
        <el-table-column prop="planQuantity" width="120" label="计划数量" align="center"></el-table-column>
        <!--        <el-table-column prop="completedQuantity" width="120"  label="已完成数量" align="center"></el-table-column>-->
        <el-table-column prop="state" label="状态" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.state === 0">创建</span>
            <span v-else-if="scope.row.state === 1">生效</span>
            <span v-else-if="scope.row.state === 2">完成</span>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="remark" width="180"  label="备注" align="center"></el-table-column>-->
        <el-table-column prop="createdBy" label="创建人" width="180" align="center"></el-table-column>
        <el-table-column prop="createdDate" width="180" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="lastModifiedBy" label="修改人" align="center"></el-table-column>
        <el-table-column prop="lastModifiedDate" width="180" label="修改时间" align="center"></el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <Button type="link" @click="viewDetail(scope.$index, scope.row)">查看</Button>
            <Button type="link" @click="editPlan(scope.$index, scope.row)">编辑</Button>
            <Button type="link" style="color:red;" @click="deletePlan(scope.$index, scope.row)">删除</Button>
          </template>
        </el-table-column>
      </el-table>

      <el-table v-if="showType === 1" :data="productionPlans" v-loading="loadingTable" style="width: 100%" :style="{ height: `${tableHeight *0.74}px` }">
        <el-table-column type="index" width="70" label="序号" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="销售订单号" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="物料名称" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="物料编码" align="center"></el-table-column>
        <el-table-column prop="" width="250" label="物料规格描述" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="订单要求" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="需求数量" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="排程数量" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="订单日期" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="制令号" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="生产任务单" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="计划发货日" align="center"></el-table-column>
        <el-table-column prop="" width="150" label="备注" align="center"></el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>

      <!-- 上传弹窗 -->
      <!-- :show-file-list="false" -->
      <ElDialog title="导入数据" v-model="uploadDialogVisible" width="40%" @close="closeDialog">
        <div style="display: flex;">
          <!-- <el-button type="primary" @click="downModel" style="margin-right: 10px;" :loading="downLoading">下载模版</el-button> -->
          <el-upload :action="''" ref="upload" class="upload-demo" :auto-upload="false" accept=".csv,.xlsx,.json,.xls" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-exceed="handleExceed" :limit="1"
            style="width: 100%;position: relative;">

            <el-button type="primary">点击上传文件</el-button>
            <!-- <template #tip>
              <div class="el-upload__tip" >只能上传一个文件</div>
            </template> -->
          </el-upload>
          <el-button type="primary" @click="downModel" style="margin-right: 10px;position: absolute;left:150px" :loading="downLoading">下载模版</el-button>

        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="confirmImport">确认导入</el-button>
          </div>
        </template>
      </ElDialog>
    </div>
  </ElCard>
</template>

<script  lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import {
  ElCard,
  ElDatePicker,
  ElPagination,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElInput,
  ElButton,
  ElFormItem,
  ElForm,
  ElMessageBox,
  ElDialog,
  ElUpload,
  ElLoading,
  ElRadioGroup,
  ElRadioButton
} from "element-plus";

import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import {
  deleteProductionPlanApi,
  getProductionPlanExport,
  getProductionPlans,
  getExportExcel,
  importProductplanExcel,
} from "#/api/productionPlan";
import { $t } from "@vben/locales";
import { Button } from "ant-design-vue";
import { cloneDeep } from "@vben/utils";
import TableHeaderFilter from "#/components/tableHeardFilter.vue";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";

const productionPlans = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchForm = reactive({
  code: null,
  planTime: null,
});
const router = useRouter();
const route = useRoute();
const tableHeight = ref(window.innerHeight);
const loadingTable = ref(true);
const uploadDialogVisible = ref(false);
const uploadFiles = ref(null);
const upload = ref<UploadInstance>();

const downLoading = ref(false);
//按单|按明细
const showType = ref(0);

// 窗口大小变化处理函数
function handleResize() {
  const screenHeight = window.innerHeight;
  const searchBarHeight = document.querySelector(".search-bar").offsetHeight;
  const actionBarHeight = document.querySelector(".action-bar").offsetHeight;
  const paginationHeight = document.querySelector(".pagination").offsetHeight;
  console.log("searchBarHeight", searchBarHeight);
  console.log("actionBarHeight", actionBarHeight);
  console.log("paginationHeight", paginationHeight);
  tableHeight.value =
    screenHeight - searchBarHeight - actionBarHeight - paginationHeight; // 减去分页条等其他元素的高度
  console.log("Screen height after resize:", screenHeight);
}
onMounted(() => {
  getProductionPlanList();
  // 监听窗口大小变化事件
  window.addEventListener("resize", handleResize);
});
// 组件卸载时移除事件监听
onUnmounted(() => {
  return () => {
    window.removeEventListener("resize", handleResize);
  };
});









// 获取生产计划列表
const getProductionPlanList = async () => {
  try {
    loadingTable.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      code: searchForm.code,
      planTimeStart: searchForm.planTime ? searchForm.planTime[0] : null,
      planTimeEnd: searchForm.planTime ? searchForm.planTime[1] : null,
    };
    const response = await getProductionPlans(params);
    productionPlans.value = response.data.content;
    console.log("res", response.data.content);
    total.value = response.data.totalElements;
    loadingTable.value = false;
  } catch (error) {
    ElMessage.error("获取生产计划列表失败");
    loadingTable.value = false;
    console.error(error);
  }
};

// 搜索功能
const search = () => {
  currentPage.value = 1;
  getProductionPlanList();
};
// 重置功能
const reset = () => {
  searchForm.code = null;
  searchForm.planTime = null;
  getProductionPlanList();
};

// 添加新计划
const addNewPlan = () => {
  window.removeEventListener("resize", handleResize);
  // 跳转到新增页面的逻辑
  router.push({ name: "planProductionAdd" });
  console.log("新增生产计划");
};

const showUpload = () => {
  uploadDialogVisible.value = true;
};

const closeDialog = () => {
  uploadDialogVisible.value = false;
  upload.value!.clearFiles();
  uploadFiles.value = null;
};

//下载模版
const downModel = async () => {
  downLoading.value = true;
  const response = await getExportExcel(); // 调用后端导出 API
  downLoading.value = false;
  if (response.status == 200) {
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    const timestamp = Date.now();
    a.setAttribute("download", `计划排产导入模版${timestamp}.xls`);
    document.body.append(a);
    a.click();
    a.remove();
    ElMessage.success("计划排产导入模版下载成功！");
  } else {
    ElMessage.error("计划排产导入模版下载失败，请稍后再试！");
  }
};

// 处理文件选择
const handleFileChange = (file) => {
  const fileType = file.name.split(".").pop().toLowerCase();
  const validTypes = ["csv", "xlsx", "json", "xls"];

  if (!validTypes.includes(fileType)) {
    ElMessage.error("不支持的文件格式，请上传 CSV、XLSX 或 JSON 文件");
    return;
  }

  uploadFiles.value = file.raw;
};

// 处理超出文件限制  只允许传一个文件
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  uploadFiles.value = files[0];
};

//移除文件
const handleFileRemove: UploadProps["onRemove"] = (file, file1) => {
  uploadFiles.value = cloneDeep(file1);
};

// 确认导入数据
const confirmImport = async () => {
  if (!uploadFiles.value || uploadFiles.value.length <= 0) {
    ElMessage.warning("请先选择文件");
    return;
  }

  const formData = new FormData();
  // console.error(uploadFiles.value);
  formData.append("file", uploadFiles.value);

  const loading = ElLoading.service({
    lock: true,
    text: "导入中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    await importProductplanExcel(formData);
    loading.close();
    await nextTick(() => {
      upload.value!.clearFiles();
      ElMessage.success("数据导入成功");
      uploadDialogVisible.value = false;
      getProductionPlanList();
    });
  } catch (error) {
    loading.close();
    ElMessage.error(`导入失败: ${error.message || "网络错误"}`);
    console.error("导入失败:", error);
  } finally {
  }
};

// 导出数据
const exportData = async () => {
  try {
    ElMessageBox.confirm("即将导出，是否继续？", "导出确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const response = await getProductionPlanExport(); // 调用后端导出 API
      if (response.status == 200) {
        const blob = response.data;
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        const timestamp = Date.now();
        a.setAttribute("download", `排产计划${timestamp}.xls`);
        document.body.append(a);
        a.click();
        a.remove();
        ElMessage.success("导出成功！");
      } else {
        ElMessage.error("导出失败，请稍后再试！");
      }
    });
  } catch (error) {
    ElMessage.error(`导出失败：${error.message}`);
  }
};

// 查看详情
const viewDetail = (index, row) => {
  window.removeEventListener("resize", handleResize);
  router.push({ name: "productionPlanDetail", params: { id: row.id } });
  console.log("查看生产计划详情:", row);
};

// 编辑计划
const editPlan = (index, row) => {
  window.removeEventListener("resize", handleResize);
  router.push({ name: "productionPlanEdit", params: { id: row.id } });
  console.log("编辑生产计划:", row);
};

// 删除计划
const deletePlan = (index, row) => {
  ElMessageBox.confirm($t("ui.actionMessage.deleting", [row.code]), {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProductionPlanApi(row.id).then(() => {
        // 删除成功后显示提示
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        //刷新
        getProductionPlanList();
      });
    })
    .catch((error) => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  getProductionPlanList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getProductionPlanList();
};


const filterChangeEvent = (parameter) => {
  const { state, filterField, selectedValue } = parameter;
  //清空操作
  if (state === 'clear') {
    if (searchForm[filterField] !== '') {
      searchForm[filterField] = '';
      search();
    }
  }

  //确定操作
  if (state === 'confirm') {
    searchForm[filterField] = selectedValue;
    if (selectedValue !== '') {
      search();
    }
  }
}
</script>

<style scoped>
.production-plan-list {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  display: flex;
  justify-content: end;
  margin-right: 20px;
  margin-top: 10px;
  width: 100%;
}

.el-table th,
.el-table td {
  border: none; /* 移除所有单元格和表头的边框 */
}
</style>
